<?php
//运营商管理
namespace app\ausadmin\controller;
use think\Request;
use think\Db;
use think\Controller;
use think\Config;
use think\File;
use think\Loader;

 class Operator extends Common
 {	
 	public function index(){
 		$pages = 20;
 		$where = 'is_delete = 1 and status = 1';
 		$pageParam    = ['query' =>[]];//分页带参数
 		//判断是否有提交数据
 		if(!empty(input('name'))){
 			$where .= ' AND name LIKE '."'%".input('name')."%' ";
 			$pageParam['query']['name'] = input('name');
 		}
 		$list=Db::name('operator')
 			 ->where($where)
 			 ->order('create_time desc')
 			 ->paginate($pages,false, $pageParam);
        //获取总设备数
        $data = $list->all();
        foreach ($data  as $k=>$v) {
            $ret = Db::name('charecabinet')
                 ->where('is_delete',1)
                 ->where('oid',$v['id'])
                 ->field('ifnull(count(id),0) as count')
                 ->find();
            $v['count'] = $ret['count'];
            $list[$k] = $v;
        }
        debug_file('----Operator-----'.Db::getLastSql());
        //var_dump($list);die;     
 		$this->assign('list',$list);	
        
 		return $this->fetch();
 	}
 	//删除运营商
 	public function delete($id=''){
 		$id =  Request::instance()->get('id','','number_int');
 		if($id){
			$data['id'] = $id;
            $data['status'] =0;
			$data['is_delete'] =0;
			if(Db::name( 'operator')->update($data)){
    			$where['oid'] = $id;//同时删除运营商下面的管理员
    			Db::name('operator_users')
    				->where($where)
    				->setField('deleted','-1');
                Db::name('smallapp')->where($where)->setField('is_delete','0');
                Db::name('wechat_mp')->where($where)->setField('is_delete',0);
                Db::name('operator_order')->where($where)->setField('is_delete',0);
                $oid = 0;$m = 'ausadmin'; $c = 'Operator'; $action="delete"; $uid=session('adminid'); $querystring = '删除代理商'.$id;
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os); 
    			return ['code'=>0, 'msg'=>lang('删除成功！')];
    		}else{
    			return ['code'=>-1050, 'msg'=>lang('删除失败！')];
    		}

		}else{
            die('非法操作');
        }
 	}
 	//更新操作
 	public function edit($id='',$data=""){
 		if ( Request::instance()->isPost() ) {

            $odata['id'] = input('id');
            $odata['name'] = input('name');
            $odata['contacts'] = input('contacts');
            $odata['mobile'] = input('mobile');
            $odata['identifying'] = input('identifying');
            $check = Db::name('operator')->where(['name'=>$odata['name'],'is_delete'=>1])->where('id','<>',$odata['id'])->find();
            if($check){
                return ['code'=>-1050, 'msg'=>lang('代理商名称已存在！')];
            }
            if(Db::name('operator')->update($odata)){
                $oid = 0;$m = 'ausadmin'; $c = 'Operator'; $action="edit"; $uid=session('adminid'); $querystring = '更新代理商信息'.input('id');
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                return ['code'=>0, 'msg'=>lang('修改成功！')];
            }else{
                return ['code'=>-1050, 'msg'=>lang('修改失败！')];
            }
 		}else{
            $id = Request::instance()->get('id','','number_int');
            if(!empty($id)){
                $where['id'] = $id;
                $userinfo = Db::name('operator')->where($where)->find();
                $ret = Db::name('version')->where('is_delete',1)->select();
                $this->assign('list',$ret);
                //判断当前版本有关的信息
                $version = Db::name('version')->where('id',$userinfo['version'])->find();
                $this->assign('vv',$version);
                $this->assign('v',$userinfo);
                return $this->fetch();
            }else{
                die('系统检测到您是非法访问!');
            }
        }
 	}

     /**
      * 添加运营商改为代理商
      * @return array|false|mixed|\PDOStatement|string|\think\Model
      */
 	public function add(){
 		if ( Request::instance()->isPost() ) {  
            $time = (int)input('expiration_date');
            if($time){
               $maturity =  strtotime("+".$time." month");
            }else{
                die('非法操作!');
            }
            $version = (int)input('version');
            if($version){
                $versionid = $version;
            }else{
                die('非法操作!');
            }
            if(strlen(input('password'))<6){
                return ['code'=>-1050, 'msg'=>lang('密码不能小于6位')];
            }
            $ver = Db::name('version')->where(['id'=>$versionid])->find();
 			$odata['name'] = input('name');
 			$odata['contacts'] = input('contacts');
 			$odata['mobile'] = input('mobile');
 			$odata['identifying'] = input('identifying');
 			$odata['version'] = $versionid;
 			$odata['expiration_date'] = $maturity;
 			$odata['types'] =1;
 			$odata['create_user'] = session("adminid");
 			$odata['create_time'] = time();
 			$odata['is_delete'] = 1;
            $validate = \think\Loader::validate('Operator'); 
            if(!$validate->scene('add')->check($odata)){
                return ['code'=>-1050, 'msg'=>$validate->getError()];
            }
 			if(Db::name('operator')->insert($odata)){
 				$oid = Db::name(Config::get('operator'))->getLastInsID();
 			}else{
 				die('添加代理商信息失败!');
 			}
 			//添加订单表
 			$order['oid'] = $oid;
 			$order['order_no'] = '201' . date('ymdHis') . rand(1000, 9999);
 			$order['payable_amount'] = $time * $ver['price'];
 			$order['real_amount'] = $time * input('price');
 			$order['pay_status'] = 0;
 			$order['version'] = $ver['id'];
 			$order['nums'] = 1;
            if($ver['free']==1){
                $order['pay_status'] =  1;
            }
 			$order['old_expiration_date'] = $maturity;
 			$order['create_user'] = session("adminid");
 			$order['create_time'] = time();
 			$order['is_delete'] = 1;
 			Db::name('operator_order')->insert($order);
            //添加小程序有关信息
            /*$app['oid'] = $oid;
            $app['status'] = 0;
            $app['version'] = $versionid;
            $app['template_id']=$ver['smapp_template_id'];
            $app['create_user'] =session('adminid');
            $app['create_time']=time();
            $app['is_delete'] =1;
            Db::name('smallapp')->insert($app);*/
 			//添加运营商管理员
 			$udata['username'] = input('username');
 			$udata['password'] = md123(input('password'));
 			$udata['phone'] = input('mobile');
 			$udata['status'] = 1;
 			$udata['register_time'] = time();
 			$udata['deleted'] = 0;
 			$udata['oid'] = $oid;
 			$uid = Db::name('operator_users')->insertGetId($udata);
 			//添加运营商管理员权限组
 			$authdata['uid'] = $uid;
 			$authdata['oid'] = $oid;
 			$authdata['group_id'] = 1;
 			if(Db::name('auth_group_relation')->insert($authdata)){
                $oid = 0;$m = 'ausadmin'; $c = 'Operator'; $action="add"; $uid=session('adminid'); $querystring = '添加代理商信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
 				return ['code'=>0, 'msg'=>lang('添加成功！')];
 			}else{
 				return ['code'=>-1050, 'msg'=>lang('添加失败！')];
 			}	
 		}
 		$ret = Db::name('version')->where('is_delete',1)->select();
 		$this->assign('list',$ret);
 		if(input('id')){
 			$id = Request::instance()->get('id','','number_int');
 			$result = Db::name('version')->where('id',$id)->find();
 			return $result;
 		}
 		return $this->fetch();
 	}

    //运营商下的管理员列表
    public function oadmin(){
        $pages = 20;
        $where = 'a.deleted = 0 and b.is_delete = 1';
        $pageParam    = ['query' =>[]];
        if(!empty(input('name'))){
            $where .= ' AND b.name LIKE '."'%".input('name')."%' ";
            $pageParam['query']['name'] = input('name');
        }
        $b = 'operator';
        $list=Db::name('operator_users')
            ->alias('a')
            ->join("$b b",'a.oid = b.id')
            ->field('a.id,a.username,b.name,b.contacts')
            ->where($where)
            ->paginate($pages,false, $pageParam);
        //var_dump($list);die;
        $this->assign('list',$list);
        
        return $this->fetch();
    }
    //重置运营商下的管理员列表
    public function editadmin($id=''){
        if ( Request::instance()->isPost() ) {
            $data['id'] = (int)input('id');
            $data['password'] = md123(input('password'));
            if(Db::name('operator_users')->update($data)){
                $oid = 0;$m = 'ausadmin'; $c = 'Operator'; $action="editadmin"; $uid=session('adminid'); $querystring = '重置'.input('id').'代理商管理员密码';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
               return ['code'=>0, 'msg'=>lang('重置密码成功！')];
            }else{
               return ['code'=>-1050, 'msg'=>lang('重置密码失败！')];
            }
        }else{
            $id = Request::instance()->get('id','','number_int');
            //echo $id;die;
            if(!empty($id)){
                $this->assign('v',$id);
                return $this->fetch();
            }else{
                die('系统检测到您是非法访问!请您马上退出!');
            }
        }
    }
    //导入机柜信息
    public function cabinet(){
        if(!empty($_FILES)){
            foreach($_FILES as $k=>$v){
                $keyname=$k;//获取提交文件数组的键名;
            }
            $tmp_file = $_FILES[$keyname]['tmp_name'];    //临时文件名
            $file_types = explode('.',$_FILES[$keyname]['name']); //  拆分文件名
            $file_type = $file_types [count ( $file_types ) - 1];   //  文件类型
            if($file_type == 'xls' || $file_type == 'xlsx'|| $file_type == 'csv'){
                /*上传文件*/
                $file = request()->file($keyname);
                $info=$file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel');
                if(!$info){                                 
                    $this->error($file->getError());         
                }
                //获取上传文件目录
                $file_name=ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel'.DS.$info->getSaveName();
                //vendor("PHPExcel.PHPExcel"); 
                //vendor("excel.PHPExcel");
                Loader::import('PHPExcel.PHPExcel');
                Loader::import('PHPExcel.PHPExcel.IOFactory');
                Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');
                $PHPExcel = new \PHPExcel();
                if($file_type=='xlsx'){
                    //设置以Excel5格式(Excel97-2003工作簿)
                    Loader::import('PHPExcel.PHPExcel.Reader.Excel2007');
                    $objReader=new \PHPExcel_Reader_Excel2007();
                   // $objReader=\PHPExcel_IOFactory::createReader('Excel2007');
                    //\PHPExcel_IOFactory::createReader('Excel5');
                }
                if($file_type=='xls'){
                    Loader::import('PHPExcel.PHPExcel.Reader.Excel5');
                    $objReader= new \PHPExcel_Reader_Excel5();
                    //$objReader=\PHPExcel_IOFactory::createReader('Excel5');
                }
                /*if($file_type=='csv'){
                    $objReader=\PHPExcel_IOFactory::createReader('CSV');
                }*/
                // 载入excel文件
                $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
                $sheet = $objPHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                //var_dump($highestRow); die;
                $j=0;
                $repeat = [];
                $oid = input('oid');
                for($i=2;$i<=$highestRow;$i++){
                    $data=null;
                    $data['cabinet_id']=$objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                    if(is_object($data['cabinet_id']))  $data['cabinet_id']= $data['cabinet_id']->__toString();
                    $data['model']=$objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
                    $data['devicenum']=$objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
                    $data['networking_card']=$objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue();
                    if(is_object($data['networking_card']))  $data['networking_card']= $data['networking_card']->__toString();
                    $data['oid'] = $oid;
                    $data['sid'] = '';
                    $data['status'] =1;
                    $data['create_user'] = session('adminid');
                    $data['create_time'] = time();
                    $data['is_delete'] = 1;
                    //var_dump($data);die;
                    $check = Db::name('charecabinet')->where('cabinet_id',$data['cabinet_id'])->where('is_delete',1)->find();
                    /*if($check){
                        return ['code'=>-1050, 'msg'=>'导入失败！表中有重复数据'.$check['cabinet_id']];
                    }
                    if(Db::name('charecabinet')->insert($data)){
                        $j++;
                    }*/
                    if($check){
                        $repeat[] = Db::name('charecabinet')->where(['is_delete'=>1,'cabinet_id'=>$data['cabinet_id']])->value('cabinet_id');
                    }else{
                        if(Db::name('portablebattery')->insert($data)){
                            $j++;
                        }
                    }
                    
                }
                //$this->success('导入成功！本次导入记录数量：'.$j); 
                $oid = 0;$m = 'ausadmin'; $c = 'Operator'; $action="cabinet"; $uid=session('adminid'); $querystring = input('oid').'运批量导入机柜信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                @unlink($file_name);
//                return ['code'=>0, 'msg'=>'导入成功！本次导入机柜数量：'.$j];
                return ['code'=>0, 'msg'=>'本次导入机柜数量为：' . $j . '；因表中重复导入失败的：' . implode(' ', $repeat)];
            }else{
                //格式不正确提示
                return ['code'=>-1050, 'msg'=>'请上传正确的excel格式的文件！'];
            }
        }/*else{
            return $this->fetch();
        }*/
        $id =  Request::instance()->get('id','','number_int');

        if(!empty($id)){
            $oid = $id;
            $this->assign('oid',$oid);
            return $this->fetch();
        }else{
            die('非法访问！');
        }
        
    }
    //导入充电宝ID
 	public function battery(){
        if(!empty($_FILES)){
            foreach($_FILES as $k=>$v){
                $keyname=$k;//获取提交文件数组的键名;
            }
            $tmp_file = $_FILES[$keyname]['tmp_name'];    //临时文件名
            $file_types = explode('.',$_FILES[$keyname]['name']); //  拆分文件名
            $file_type = $file_types [count ( $file_types ) - 1];   //  文件类型
            if($file_type == 'xls' || $file_type == 'xlsx'|| $file_type == 'csv'){
                /*上传文件*/
                $file = request()->file($keyname);
                $info=$file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel');
                if(!$info){                                 
                    $this->error($file->getError());         
                }
                //获取上传文件目录
                $file_name=ROOT_PATH . 'public' . DS . 'uploads'.DS.'excel'.DS.$info->getSaveName();
                //vendor("PHPExcel.PHPExcel"); 
                //vendor("excel.PHPExcel");
                Loader::import('PHPExcel.PHPExcel');
                Loader::import('PHPExcel.PHPExcel.IOFactory');
                Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');
                $PHPExcel = new \PHPExcel();
                if($file_type=='xlsx'){
                    //设置以Excel5格式(Excel97-2003工作簿)
                    Loader::import('PHPExcel.PHPExcel.Reader.Excel2007');
                    $objReader= new \PHPExcel_Reader_Excel2007();
                    
                }
                if($file_type=='xls'){
                    Loader::import('PHPExcel.PHPExcel.Reader.Excel5');
                    $objReader= new \PHPExcel_Reader_Excel5();
                    //$objReader=\PHPExcel_IOFactory::createReader('Excel5');
                }
                /*if($file_type=='csv'){
                    $objReader= new \PHPExcel_IOFactory::createReader('CSV');
                }*/
                // 载入excel文件
                $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
                $sheet = $objPHPExcel->getSheet(0); // 读取第一個工作表
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                $j=0;
                $repeat = [];
                $oid = input('oid');
                for($i=2;$i<=$highestRow;$i++){
                    $data=null;
                    $data['device_id']=$objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                    if(is_object($data['device_id']))  $data['device_id']= $data['device_id']->__toString();
                    $data['oid'] = $oid;
                    $data['create_user'] = session('adminid');
                    $data['create_time'] = time();
                    $data['is_delete'] = 1;
                    //var_dump($data);die;
                    $check = Db::name('portablebattery')->where(['is_delete'=>1,'device_id'=>$data['device_id']])->find();
                    if($check){
                        $repeat[] = Db::name('portablebattery')->where(['is_delete'=>1,'device_id'=>$data['device_id']])->value('device_id');
//                        return ['code'=>-1050, 'msg'=>'导入失败！表中有重复数据'.$check['device_id']];
                    }else{
                        if(Db::name('portablebattery')->insert($data)){
                            $j++;
                        }
                    }
                }
                //$this->success('导入成功！本次导入记录数量：'.$j);
                $oid = 0;$m = 'ausadmin'; $c = 'Operator'; $action="battery"; $uid=session('adminid'); $querystring = input('oid').'运批量导入充电宝信息';
                $ip = get_ip();$os = get_os();
                set_logs($oid,$m,$c,$action,$uid,$querystring,$ip,$os);
                @unlink($file_name);
                return ['code'=>0, 'msg'=>'本次导入充电宝数量为：' . $j . '；因表中重复导入失败的：' . implode(' ', $repeat)];
            }else{
                //格式不正确提示
                return ['code'=>-1050, 'msg'=>'请上传正确的excel格式的文件！'];
            }
        }
        $id =  Request::instance()->get('id','','number_int');

        if(!empty($id)){
            $oid = $id;
            $this->assign('oid',$oid);
            return $this->fetch();
        }else{
            die('非法访问！');
        }
    }
    public function times(){
        $id = (int)input('id');
        $time = (int)input('t');
        //$times = strtotime('+'.$id.' month',$time);
        //$date = date('Y-m-d H:i:s',$times);
        $data = date("Y-m-d", strtotime("+".$id." months", $time));
        $data = '修改成功后到期日将更新至'.$data.',请谨慎操作';
        return $data;
        
    }

    public function info(){
        $id = (int)input('id');
        if($id){
            $ret = Db::name('operator')->where(['id'=>$id])->find();
            $order = Db::name('operator_order')->where(['oid'=>$id,'is_delete'=>1])->select();
            debug_file(Db::name('operator_order')->where(['oid'=>$id,'is_delete'=>1,'old_expiration_date'=>$ret['expiration_date']])->whereor('new_expiration_date',$ret['expiration_date'])->fetchSql()->find());
            $check = Db::name('operator_order')->where(['oid'=>$id,'is_delete'=>1,'old_expiration_date'=>$ret['expiration_date']])->whereor('new_expiration_date',$ret['expiration_date'])->find();
            $ver = Db::name('version')->where('id',$ret['version'])->find();
            //统计商户数:
            $sell = Db::name('seller')->where(['oid'=>$ret['id'],'is_delete'=>1,'status'=>1])->count('id');

            //统计用户数:
            $users = Db::name('user')->where(['oid'=>$ret['id'],'is_delete'=>1])->count('distinct(openid)');
            //统计机柜数:
            $cabinet = Db::name('charecabinet')->where(['oid'=>$ret['id'],'is_delete'=>1,'status'=>1])->count('distinct(cabinet_id)');
            //统计充电宝数:
            $battery = Db::name('portablebattery')->where(['oid'=>$ret['id'],'is_delete'=>1,'status'=>1])->count('distinct(device_id)');
            if(!$order){
                $order = 0 ;
            }
            $this->assign('sell',$sell);
            $this->assign('users',$users);
            $this->assign('cabinet',$cabinet);
            $this->assign('battery',$battery);
            $this->assign('list',$order);
            $this->assign('v',$check);
            $this->assign('ver',$ver);
            $this->assign('ret',$ret);
             
            return $this->fetch();
        }else{
            die('非法操作');
        }
    }

}
